const fs = require('fs')
const path = require('path')

// 对 num 进行前置补零, 确保 num 占 digit 位
function formatNum(num, digit = 2) {
    const _digit = digit
    if (digit > 5) return num
    while (digit-- > 0) num = '0' + num
    return num.substring(num.length - _digit)
}

// 年-月-日
function getToday() {
    const date = new Date()
    return (
        date.getFullYear() +
        '-' +
        formatNum(date.getMonth() + 1) +
        '-' +
        formatNum(date.getDate())
    )
}

// 时:分:秒
function getTime() {
    const date = new Date()
    return (
        formatNum(date.getHours()) +
        ':' +
        formatNum(date.getMinutes()) +
        ':' +
        formatNum(date.getSeconds())
    )
}

function logError(error) {
    console.error(error.message)
    fs.appendFile(
        path.join(__dirname, `../log/error-${getToday()}.log`),
        '\n' +
            `时间: ${getTime()};` +
            `name: ${error.name};` +
            `message: ${error.message};` +
            `case: ${error.case};\n` +
            error.stack +
            '\n',
        () => {}
    )
}

function getSoleStr() {
    return Math.random() + '' + new Date().getTime()
}

module.exports = {
    logError,
    getSoleStr,
}
